package com.chenjun.core.service.sys.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chenjun.common.bean.Pagination;
import com.chenjun.common.model.DataGridModel;
import com.chenjun.core.auth.encoder.EncodingUtils;
import com.chenjun.core.dao.generator.entity.SysUser;
import com.chenjun.core.dao.generator.entity.SysUserGroup;
import com.chenjun.core.dao.generator.entity.SysUserRole;
import com.chenjun.core.dao.generator.mapper.SysUserMapper;
import com.chenjun.core.dao.module.SysUserRelationMapper;
import com.chenjun.core.service.activiti.SynUserGroupToActivitiService;
import com.chenjun.core.service.activiti.SynUserRoleToActivitiService;
import com.chenjun.core.service.activiti.SynUserToActivitiService;
import com.chenjun.core.service.sys.SysUserGroupService;
import com.chenjun.core.service.sys.SysUserRoleService;
import com.chenjun.core.service.sys.SysUserService;
import com.chenjun.core.vo.sys.UserBean;
import com.chenjun.core.vo.sys.UserRoleBean;

@SuppressWarnings("serial")
@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

	private static final String USER_MAPPER = "UserMapper";
	private static final Logger logger = Logger.getLogger(SysUserServiceImpl.class);

	@Autowired
	private SysUserMapper sysUserMapper;
	
	@Autowired
	private SysUserRelationMapper sysUserRelationMapper;

	@Autowired
	private SysUserRoleService sysUserRoleService;
	
	@Autowired
	private SysUserGroupService sysUserGroupService;
	
	@Autowired
	private SynUserToActivitiService synUserService;
	
	@Autowired
	private SynUserRoleToActivitiService synUserRoleService;
	
	@Autowired
	private SynUserGroupToActivitiService synUserGroupService;

	public SysUser get(String id) {
		return sysUserMapper.selectByPrimaryKey(id);
	}

	public int create(SysUser record) {
		return sysUserMapper.insert(record);
	}

	public int delete(String id) {
		int result = -1;
		SysUser user = this.get(id);
		if (null != user) {
			// 查询关联角色
			DataGridModel dgm = new DataGridModel();
			Map<String, Object> param = new HashMap<String, Object>(1);
			param.put("userId", id);
			dgm.setParams(param);
			dgm.setRows(0);
			List<UserRoleBean> urbs = sysUserRoleService.dofListByCondition(dgm);
			// 删除
			Map<String, String> params = new HashMap<String, String>(1);
			params.put("userId", id);
			result = sysUserRoleService.deleteByCondition(params);
			if (result > 0) {
				result = sysUserMapper.deleteByPrimaryKey(id);
				
				// 同步到activiti中
				for(UserRoleBean urb : urbs){
					SysUserRole ur = new SysUserRole();
					ur.setRoleId(urb.getRoleId());
					ur.setUserId(urb.getUserId());
					synUserRoleService.deleteMembership(ur);
				}
				synUserService.deleteUser(id);
			}
		}
		return result;
	}

	public int update(SysUser record) {
		return sysUserMapper.updateByPrimaryKey(record);
	}

	public int createOrUpdate(SysUser record) {
		int rows = 0;

		record.setPassword(EncodingUtils.getEncodedPwd(record.getPassword()));// 密码加密

		if (StringUtils.isBlank(record.getId())) {
			rows = sysUserMapper.insert(record);

		} else {
			rows = sysUserMapper.updateByPrimaryKeySelective(record);
		}
		return rows;
	}

	public int editUser(SysUser record) {
		int rows = 0;

		if (StringUtils.isBlank(record.getId())) {
			rows = sysUserMapper.insert(record);

		} else {
			rows = sysUserMapper.updateByPrimaryKeySelective(record);
		}
		return rows;
	}

	/**
	 * 添加用户和角色名
	 * 
	 * @param record
	 * @return int
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	public int createOrUpdate(UserBean record) throws IllegalAccessException, InvocationTargetException {
		int rows = 0;

		record.setPassword(EncodingUtils.getEncodedPwd(record.getPassword()));// 密码加密

		SysUser user = UserBean.getModelByBean(record);
		SysUserRole ur = new SysUserRole();
		SysUserGroup ug = new SysUserGroup();

		if (StringUtils.isBlank(record.getId())) {
			user.setCreatedTime(Calendar.getInstance().getTime());
			user.setPassword(EncodingUtils.getEncodedPwd("123456"));
			String userID = UUID.randomUUID().toString(); // 后端直接生成ID，用于后期处理
			user.setId(userID);
			record.setId(userID);
			rows = sysUserMapper.insert(user);
			ur.setRoleId(record.getRoleId());
			ur.setUserId(userID);
			rows = sysUserRoleService.create(ur);
			ug.setGroupId(record.getGroupId());
			ug.setUserId(userID);
			rows = sysUserGroupService.create(ug);
			// 同步到activiti中
			synUserService.saveUser(record);
			synUserRoleService.addMembership(ur);
			synUserGroupService.addMembership(ug);
		} else {
			// 查询关联角色
			DataGridModel dgm = new DataGridModel();
			Map<String, Object> param = new HashMap<String, Object>(1);
			param.put("userId", record.getId());
			dgm.setParams(param);
			dgm.setRows(0);
			List<UserRoleBean> urbs = sysUserRoleService.dofListByCondition(dgm);
			
			Map<String, String> params = new HashMap<String, String>(1);
			params.put("userId", record.getId());
			rows = sysUserRoleService.deleteByCondition(params);
			sysUserGroupService.deleteByCondition(params);
			if (rows > 0) {
				rows = sysUserMapper.updateByPrimaryKeySelective(user);
				ur.setRoleId(record.getRoleId());
				ur.setUserId(user.getId());
				rows = sysUserRoleService.create(ur);
				ug.setGroupId(record.getGroupId());
				ug.setUserId(user.getId());
				rows = sysUserGroupService.create(ug);
				
				// 同步到activiti中
				for(UserRoleBean urb : urbs){
					SysUserRole sur = new SysUserRole();
					sur.setRoleId(urb.getRoleId());
					sur.setUserId(urb.getUserId());
					synUserRoleService.deleteMembership(sur);
				}
			}
		}
		return rows;
	}

	public int doCountByCondition(DataGridModel param) {
		return sysUserRelationMapper.countByCondition(param);
	}

	public List<SysUser> doListByCondition(DataGridModel param) {
		return sysUserRelationMapper.selectByCondition(param);
	}

	public Pagination doPagination(DataGridModel param) {
		Pagination vo = new Pagination();
		List<SysUser> list = sysUserRelationMapper.selectByCondition(param);
		param.setStart(0);
		param.setRows(0);
		int size = sysUserRelationMapper.countByCondition(param);
		vo.setAaData(list);
		vo.setiTotalRecords(size);
		vo.setsEcho(param.getPage());
		vo.setiTotalDisplayRecords(size);
		return vo;
	}

	@Override
	public void deleteActivitiData(String id) {
		SysUser user = this.get(id);
		if (null != user) {
			// 查询关联角色
			DataGridModel dgm = new DataGridModel();
			Map<String, Object> param = new HashMap<String, Object>(1);
			param.put("userId", id);
			dgm.setParams(param);
			dgm.setRows(0);
			List<SysUserRole> urbs = sysUserRoleService.doListByCondition(dgm);
			// 删除activiti中关联用户角色
			for(SysUserRole ur : urbs){
				synUserRoleService.deleteMembership(ur);
			}
			List<SysUserGroup> ugs = sysUserGroupService.doListByCondition(dgm);
			for(SysUserGroup ug : ugs){
				synUserGroupService.deleteMembership(ug);
			}
			synUserService.deleteUser(id);
		}
	}

	
}
